package project.ekko.listener;

import project.ekko.listener.processor.ExitProcessor;
import project.ekko.listener.processor.FishProcessor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;

public class KeyPressed {

    static final Logger log = Logger.getGlobal();

    private static final BlockingQueue<KeyEvent> QUEUE = new LinkedTransferQueue<>();

    private static final List<Consumer<KeyEvent>> ACTIONS = new ArrayList<>();

    static {
        ACTIONS.add(new ExitProcessor());
        log.info("Exit processor has been registered!");
        ACTIONS.add(new FishProcessor());
        log.info("Fish processor has been registered!");
        var thread = new Thread(() -> {
            while (true) {
                try {
                    execute(QUEUE.take());
                } catch (Exception ex) {
                    log.log(Level.SEVERE, "bang", ex);
                }
            }
        });
        thread.setName("ekko");
        thread.start();
    }

    public static void pressed(KeyEvent event) {
        QUEUE.add(event);
    }

    private static void execute(KeyEvent event) {
        ACTIONS.forEach(action -> action.accept(event));
    }
}
